from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
                             QScrollArea, QGridLayout, QMessageBox, QSizePolicy)
from PyQt5.QtCore import Qt, QDateTime, QTimer
from PyQt5.QtGui import QPixmap, QFont, QColor, QPainter, QBrush, QPen
from PyQt5.QtGui import QPainterPath
import base64
from dao.index import LoginSchema
from utils.json import JSONHandler
from dao.exam import Exam
from dao.classRecord import classRecord
from utils.recognition import FaceRecognition
from datetime import datetime
from components.messageBox import CustomMessageBox

class StHome(QWidget):
    """学生主页视图"""
    def __init__(self):
        super().__init__()
        self.json = JSONHandler("./config/cache.json")
        self.initUI()
        self.load_sample_data()
        self.setup_stylesheet()
        
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_exam_status)
        self.timer.start(1000)

    def initUI(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)

        self.create_profile_section(main_layout)
        self.create_exam_section(main_layout)

    def get_user(self):
        login_schema = LoginSchema().get_student(user_id=self.json.read()["user_id"])
        return login_schema

    def create_profile_section(self, parent_layout):
        profile_widget = QWidget()
        profile_layout = QHBoxLayout(profile_widget)
        profile_layout.setContentsMargins(0, 0, 0, 0)
        profile_layout.setSpacing(30)

        # 左侧信息
        info_widget = QWidget()
        grid_layout = QGridLayout(info_widget)
        grid_layout.setVerticalSpacing(12)

        curstudent = self.get_user()
        self.curstu = curstudent
        self.profile_info = {
            '姓名': curstudent['name'],
            '学号': curstudent['student_number'],
            '性别': '男' if curstudent['gender'] == 1 else "女",
            '班级': curstudent['class_name'],
            '入学日期': curstudent['enrollment_date'] if curstudent['enrollment_date'] else "未知",
            '邮箱': curstudent['email'] if curstudent['email'] else "未设置"
        }

        row = 0
        for key, value in self.profile_info.items():
            grid_layout.addWidget(QLabel(f"<b>{key}:</b>"), row, 0)
            grid_layout.addWidget(QLabel(value), row, 1)
            row += 1

        # 右侧头像（圆形显示）
        self.avatar_label = QLabel()
        self.load_avatar()  # 使用默认头像
        # 设置距离右边有一定距离
        profile_layout.setContentsMargins(0, 0, 20, 0)  # 右边距设为20像素
        profile_layout.addWidget(info_widget)
        profile_layout.addWidget(self.avatar_label, alignment=Qt.AlignRight)
        parent_layout.addWidget(profile_widget)

    def load_avatar(self):
        try:
            # 从当前用户信息中获取头像路径（假设路径存储在self.curstu['avatar_path']）
            avatar_path = self.curstu.get('avatar_path', '')  # 或动态生成路径，例如：f"avatars/{self.curstu['id']}.png"
            
            # 尝试加载头像文件
            pixmap = QPixmap(avatar_path)
            if pixmap.isNull():
                raise ValueError("头像文件无效或路径错误")
                
            # 可选：缩放或调整图像大小
            # pixmap = pixmap.scaled(80, 112, Qt.KeepAspectRatio, Qt.SmoothTransformation)

        except Exception as e:
            # 生成默认头像
            pixmap = QPixmap(80, 112)
            pixmap.fill(Qt.transparent)
            painter = QPainter(pixmap)
            painter.setRenderHint(QPainter.Antialiasing)
            # 设置背景色为浅紫色
            painter.setBrush(QBrush(QColor("#bdc3c7")))
            painter.setPen(QPen(Qt.NoPen))
            painter.drawRect(0, 0, 80, 112)
            # 使用用户姓名的首字母作为默认头像
            painter.setFont(QFont("Microsoft YaHei", 24))
            painter.setPen(QPen(Qt.white))
            name = self.curstu['name'][0] if self.curstu['name'] else ''
            painter.drawText(pixmap.rect(), Qt.AlignCenter, name)
            painter.end()
        circular_pixmap = QPixmap(pixmap.size())
        circular_pixmap.fill(Qt.transparent)
        painter = QPainter(circular_pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawPixmap(0, 0, pixmap)
        painter.end()
        # 显示头像
        self.avatar_label.setPixmap(circular_pixmap)
        self.avatar_label.setFixedSize(80, 112)

    def create_exam_section(self, parent_layout):
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
            }
            QScrollBar:vertical, QScrollBar:horizontal {
                width: 0;
                height: 0;
                background: transparent;
            }
        """)


        container = QWidget()
        self.exam_layout = QGridLayout(container)
        self.exam_layout.setContentsMargins(0, 0, 0, 20)
        self.exam_layout.setHorizontalSpacing(20)
        self.exam_layout.setVerticalSpacing(20)

        scroll_area.setWidget(container)
        parent_layout.addWidget(scroll_area)

    def load_sample_data(self):
        user = LoginSchema().get_student(user_id=self.json.read()["user_id"])
        exam = Exam().get_calss_exam(user['class_name'])
        print("考试数据=============",exam)
        self.exams = [
            {
                "subject": i["exam_name"],
                "exam_time": QDateTime.fromString(i['start_time'].strftime('%Y-%m-%d %H:%M:%S'), "yyyy-MM-dd hh:mm:ss"),
                "deadline": QDateTime.fromString(i['start_time'].strftime('%Y-%m-%d %H:%M:%S'), "yyyy-MM-dd hh:mm:ss"),
                "class": i['class_name']
            }  for i in exam]

        # 设置 QGridLayout 的列宽，使两列均分
        self.exam_layout.setColumnStretch(0, 1)
        self.exam_layout.setColumnStretch(1, 1)

        for idx, exam in enumerate(self.exams):
            self.create_exam_card(idx, exam)

    def create_exam_card(self, index, exam_data):
        card = QWidget()
        card.setMinimumWidth(220)
        card.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        # 设置卡片的样式，去掉左右边距
        card.setStyleSheet("""
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin: 14px;
        """)

        layout = QVBoxLayout(card)

        # 创建科目和状态的水平布局
        subject_layout = QHBoxLayout()
        
        # 科目标签
        subject_label = QLabel(exam_data["subject"])
        subject_label.setStyleSheet("font-size: 18px; font-weight: 600; color: #2c3e50;")
        
        # 状态标签（靠右显示）
        status_label = QLabel()
        status_label.setAlignment(Qt.AlignRight)
        status_label.setStyleSheet("color: red; font-size: 14px;")
        
        # 添加部件到水平布局
        subject_layout.addWidget(subject_label)
        subject_layout.addStretch()  # 添加弹簧使状态标签靠右
        subject_layout.addWidget(status_label)

        # 判断是否缺考
        current_time = QDateTime.currentDateTime()
        if current_time > exam_data["deadline"]:
            status_label.setText("已经缺考")

        time_style = """
            QLabel {
                color: #7f8c8d;
                font-size: 14px;
                padding: 8px 12px;
                background: #f8f9fa;
                border-radius: 6px;
            }
        """

        exam_time = QLabel(f"🕒 {exam_data['exam_time'].toString('yyyy-MM-dd hh:mm')}")
        exam_time.setStyleSheet(time_style)

        deadline = QLabel(f"⏳ {exam_data['deadline'].toString('yyyy-MM-dd hh:mm')}")
        deadline.setStyleSheet(time_style)

        btn_sign = QPushButton("立即签到")
        btn_sign.setCursor(Qt.PointingHandCursor)
        btn_sign.clicked.connect(lambda _, e=exam_data: self.handle_signin(e))
        btn_sign.setStyleSheet("""
            QPushButton {
                background: #27ae60;
                color: white;
                border: none;
                padding: 10px 24px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
            }
            QPushButton:hover { background: #219a52; }
            QPushButton:disabled {
                background: #95a5a6;
                color: #ecf0f1;
            }
        """)

        # 添加布局和部件
        layout.addLayout(subject_layout)  # 添加水平布局
        layout.addWidget(exam_time)
        layout.addWidget(deadline)
        layout.addWidget(btn_sign, alignment=Qt.AlignRight)

        row = index // 2
        col = index % 2
        self.exam_layout.addWidget(card, row, col)
        

    def handle_signin(self, exam_data):
        current_time = QDateTime.currentDateTime()
        if current_time > exam_data["deadline"]:
            QMessageBox.warning(self, "签到失败", 
                f"<b>{exam_data['subject']}</b><br>"
                "已超过签到截止时间15分钟，本次考试记为缺考！")
        else:
            user = LoginSchema().get_student(self.json.read()['user_id'])
            teacher_name = Exam().get_calss_by_exam(exam_data['subject'])
            cord = classRecord().get_class(user['name'])
            if cord:
                CustomMessageBox().show_error("请勿重复签到")
                return
            teacher = LoginSchema().get_teacher(teacher_name['teacher_id'])
            face = FaceRecognition()
            face.add_face()
            face.run(user['en_name'])
            # 组装数据
            ans = {
                'exam_name' : exam_data['subject'],
                'student_number' : self.json.read()['user_id'],
                'student_name': user['name'],
                'exam_class': exam_data['class'],
                'teacher_name': teacher['name'],
                'sign_in_time': datetime.now(),
                'exam_start_time': teacher_name['start_time']
            }
            classRecord().insert_cord(ans)


    def update_exam_status(self):
        current_time = QDateTime.currentDateTime()
        for i in range(len(self.exams)):
            card = self.exam_layout.itemAt(i).widget()
            btn = card.findChild(QPushButton)
            exam_data = self.exams[i]
            btn.setDisabled(current_time > exam_data["deadline"])

    def setup_stylesheet(self):
        self.setStyleSheet("""
            QWidget {
                background: #f8f9fa;
                font-family: 'Microsoft YaHei';
            }
            QScrollArea {
                border-top: 1px solid #e0e0e0;
                margin-top: 20px;
            }
        """)

    def showEvent(self, event):
        """重写showEvent方法，在页面显示时刷新数据"""
        super().showEvent(event)
        self.refresh_data()

    def refresh_data(self):
        curstudent = self.get_user()
        self.curstu = curstudent
        self.profile_info = {
            '姓名': curstudent['name'],
            '学号': curstudent['student_number'],
            '性别': '男' if curstudent['gender'] == 1 else "女",
            '班级': curstudent['class_name'],
            '入学日期': curstudent['enrollment_date'] if curstudent['enrollment_date'] else "未知",
            '邮箱': curstudent['email'] if curstudent['email'] else "未设置"
        }

        # 更新头像
        self.load_avatar()

        # 重新加载考试数据
        self.load_sample_data()

        # 更新考试状态
        self.update_exam_status()